# AttackAnalyzerApp Class handles the interaction for user.
# it creates GUI, prompt user for input
# Inputs are .txt file containing the list of md5s

# e.g. 
# ca019adaad22da805b5188dd4025f2ff
# 3cc9971f0b36eb7224e631983ab9fe04

# result is to be accessed on "View Results" button
# and to be viewed as html file


# imports
from tohtml import SummaryToHTML
from exception import NetworkError, ThreatNameError, TraitError
from comparator import Comparator 
import Tkinter as tk
from Tkinter import *
import tkFileDialog 
import webbrowser
import json
import time
url = "http://sre-api.gist.symantec.com/"

class AttackAnalyzerApp(tk.Frame):

    def __init__(self, master):
        # Initialize window using the parent's constructor
        tk.Frame.__init__(self, master)
         
        # Set GUI components
        self.master.title('Attack Analyzer')
        self.master.geometry("515x230")
        self.iframe1 = LabelFrame(self.master, text=" First file: ", bd=1, relief=GROOVE, pady = 4)
        self.iframe2 = LabelFrame(self.master, text=" Second file: ", bd=1, relief=GROOVE, pady = 4)
        self.iframe3 = Frame(self.master, bd=1, relief=FLAT)
        
        self.iframe1.grid(row=2, column=1, padx="2m", pady="2m")
        self.iframe2.grid(row=3, column=1, padx="2m", pady="2m")
        self.iframe3.grid(row=4, column=1, padx="2m", pady="2m")
        
        self.e1 = tk.Entry(self.iframe1, width=60, bd=2)
        self.e2 = tk.Entry(self.iframe2, width=60, bd=2)
        self.b1 = tk.Button(self.iframe1, text='Browse..', width=10, bd=2, command=self.getFileNameInput1)
        self.b2 = tk.Button(self.iframe2, text='Browse..', width=10, bd=2, command=self.getFileNameInput2)
        self.b3 = tk.Button(self.iframe3, text='Compare', width=24, command=self.main)
        self.b4 = tk.Button(self.iframe3, text='View results', width=24, command=self.viewResults, state=DISABLED)
        self.b5 = tk.Button(self.iframe3, text='>> From FTP', width=12, command=self.getFTP, background="cadetblue")
         
        self.e1.grid(row=1, padx="3m", pady="2m")
        self.e2.grid(row=4, padx="3m", pady="2m")
        self.b1.grid(row=1, column=1, padx="3m", pady="1m")
        self.b2.grid(row=4, column=1, padx="3m", pady="1m")
        self.b3.grid(row=7, column=1, padx="2m", pady="2m")
        self.b4.grid(row=7, column=2, padx="2m", pady="2m")
        self.b5.grid(row=7, column=0, padx="2m", pady="2m")
        
        # initialise attributes
        self.filename1=""
        self.filename2=""
        self.filenameInput1 =""
        self.filenameInput2 =""
        self.firstList=[]
        self.secondList=[]
        self.threatNameComparisonData={}
        self.networkHostComparisonData={}
        self.networkIPLocationComparisonData={}
        self.networkFileComparisonData={} 
        self.traitComparisonData={}
        self.traitComResStats={}
        
        self.threatNameSummary={}
        self.hostSummary={}
        self.ipLocationSummary={}
        self.networkFileSummary={}
        self.traitSummary={}
        self.traitTypeSummary={}
        self.summary={}
  
    # run the app with main loop
    def run(self):
        self.mainloop()
    
    # triggered by b1 - Browse button 1
    def getFileNameInput1(self):
        if self.e1.get():
            self.e1.delete(0, END)
       
        self.filenameInput1 = tkFileDialog.askopenfilename(filetypes = (("Text files", "*.txt")
                                                        ,("All files", "*.*")))
        if self.filenameInput1:
            self.e1.insert(0, self.filenameInput1)
        else:
            print("File 1 doesn't exist!")

    # triggered by b2 - Browse button 2
    def getFileNameInput2(self):
        if self.e2.get():
            self.e2.delete(0, END)
            
        self.filenameInput2 = tkFileDialog.askopenfilename(filetypes = (("Text files", "*.txt")
                                                        ,("All files", "*.*")))
        if self.filenameInput2:
            self.e2.insert(0,self.filenameInput2)
        else:
            print("File 2 doesn't exist!")
    
    # method to open files from filename inputs
    def askopenfile(self):
        try:
            self.filename1 = open(self.filenameInput1, 'r')
            self.filename2 = open(self.filenameInput2, 'r')
        except:
            print ("File open causes error, please check file names")
    
    # method to read file line by line     
    def readFile(self):
        try:
            for line in self.filename1.readlines():
                self.firstList.append(line.rstrip('\n'))
            
            for line in self.filename2.readlines():
                self.secondList.append(line.rstrip('\n'))
        finally:
            pass
        
    # method to get input from Entries
    def getInput(self):  
        self.filenameInput1 = self.e1.get()
        self.filenameInput2 = self.e2.get()
    
    # method to handle threat name comparison
    def compareThreatNames(self):
        try:
            print ("Status: Comparing Threat Names")
            self.threatNameComparisonData = self.comp.getThreatCompRes()
    
            self.threatNameSummary['Threat Name'] = {"Threat Name Similarity": self.comp.noOfThreatNameSimilarity,
                                                     "Threat Name in set A": self.comp.noOfThreatInListA,
                                                     "Threat Name in set B": self.comp.noOfThreatInListB}
#             print self.threatNameSummary
            print ("Results : Successful")
            
        except ThreatNameError,e:
            e.printError()
        finally:
            print ("Done comparing Threat Names\n")
    # method to handle network comparison   
    def compareNetwork(self):
        try:
            print ("Status: Comparing Network")
            
            self.networkHostComparisonData = self.comp.networkHostResult
            self.networkIPLocationComparisonData = self.comp.networkIPLocationResult
            self.networkFileComparisonData = self.comp.networkFileResult
      
            self.hostSummary['Host'] = {"Host Similarity": self.comp.noOfNetworkHostSimilarity,
                                        "Host in set A": self.comp.NoOfNetworkHostInListA,
                                        "Host in set B": self.comp.NoOfNetworkHostInListB}
            self.ipLocationSummary['IP Location'] = {"IP Location Similarity": self.comp.noOfNetworkIPLocationSimilarity,
                                        "IP Location in set A": self.comp.noOfNetworkIPLocationInListA,
                                        "IP Location in set B": self.comp.noOfNetworkIPLocationInListB}
            self.networkFileSummary['Network Files'] = {"Network Files Similarity": self.comp.noOfNetworkFileSimilarity,
                                        "Network Files in set A": self.comp.noOfNetworkFileInListA,
                                        "Network Files in set B": self.comp.noOfNetworkFileInListB}         
#             print self.hostSummary
#             print self.ipLocationSummary
#             print self.networkFileSummary
            print ("Results : Successful")
            
        except NetworkError,e:
            e.printError()
        finally:
            print ("Done comparing Network\n")
    # method to handle trait comparison       
    def compareTraits(self):
        try:
            print ("Status: Comparing Traits")
            self.traitComparisonData = self.comp.getTraitCompRes()   
            self.traitComResStats = self.comp.getTraitComResStats(self.traitComparisonData)         
            self.traitSummary['Trait'] = {"Trait Similarity": self.comp.noOfTraitSimilarity,
                                        "Trait in set A": self.comp.noOfTraitInListA,
                                        "Trait in set B": self.comp.noOfTraitInListB}
            
            for category in self.traitComparisonData:
                traitTypeSummaryDetails = {}
                traitTypeSummaryDetails[category + " Similarity"] = len(self.traitComparisonData[category])
                traitTypeSummaryDetails[category + " in set A"] = self.comp.traitObjectNoDictInListA[category]
                traitTypeSummaryDetails[category + " in set B"] = self.comp.traitObjectNoDictInListB[category]
                self.traitTypeSummary[category] = traitTypeSummaryDetails
                
            print ("Results : Successful")
        except TraitError,e:
            e.printError()
        finally:
            print ("Done comparing Traits\n")
    
    def openfilehardcode(self):
        self.filenameInput1 = 'set1.txt'
        self.filenameInput2 = 'set2.txt'
    # main execution
    def main(self):
        # get 2 file name inputs from the Entry
#         self.openfilehardcode()
        self.getInput()
        self.askopenfile()
        
        if self.filename1 and self.filename2:
#             try:
            # start reading file
            self.readFile()
            
            # record start time of execution
            start_time = time.time()
            
            # initialise comparator object with the 2 lists of MD5s
            self.comp = Comparator(self.firstList, self.secondList) 
            
            # start compare Network - Host, IP Location and Network files
            # write to HTML
            self.compareNetwork()
            
            # start compare Traits
            # write to HTML
            self.compareTraits()
            
            # start compare Threat Names
            # write to HTMl
            self.compareThreatNames()
            
            # summary
            self.summary = dict(self.threatNameSummary.items() + self.hostSummary.items() 
                                + self.ipLocationSummary.items() + self.networkFileSummary.items()
                                + self.traitSummary.items() + self.traitTypeSummary.items())
            htmlFile = SummaryToHTML(self.summary, self.threatNameComparisonData, self.networkHostComparisonData, 
                                     self.networkIPLocationComparisonData, self.networkFileComparisonData,
                                     self.traitComparisonData, self.traitComResStats)
            htmlFile.execute()
            
            # display the time of execution
            print "Time taken:", time.time() - start_time, "seconds"
            
            # enable "view result" button
            self.b4.config(state='normal')
            
#             except:
#                 print ('processing failed')
#                 print ('i am at pass')
        else:
            print ("Please input the .txt file")

    # triggered by b4 - "View Result" button\
    
    def viewResults(self):
        new = 2 # open in a new tab, if possible
        url = "SummaryData.html"
        webbrowser.open(url,new=new)


#########################################################################
##                             main fuction                            ##
#########################################################################

    def getFTP(self):
        print "yay"
        
        
root = Tk()   
img = PhotoImage(file='icon\\image32.gif')
root.tk.call('wm', 'iconphoto', root._w, img)
app = AttackAnalyzerApp(root)
app.run()